package com.edu.whty.common.tools;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public final class BeanUtils {
	
	private static final Logger LOGGER = LogManager.getLogger(BeanUtils.class);
	
	public static void putFields(Object srcBean, Object destBean) {
		if (srcBean != null && destBean != null) {
			Class<?> srcClazz = srcBean.getClass();
			Class<?> destClazz = destBean.getClass();
			Field[] fields = srcClazz.getDeclaredFields();
			for (Field field : fields) {
				String fieldName = field.getName();
				String setMethod = "set" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
				try {
					Method method = destClazz.getDeclaredMethod(setMethod, new Class<?>[]{field.getType()});
					if (!method.isAccessible()) {
						method.setAccessible(true);
					}
					method.invoke(destBean, field.get(srcClazz));
				} catch(NoSuchMethodException ex) {
					LOGGER.error(ex.getMessage());
					continue;
				} catch(InvocationTargetException ex) {
					LOGGER.error(ex.getMessage(), ex);
					continue;
				} catch(IllegalAccessException ex) {
					LOGGER.error(ex.getMessage(), ex);
					continue;
				}
			}
		}
	}
	
	/**
	 * javaBean转map
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> beanToMap(Object obj) { 
        Map<String, Object> params = new HashMap<String, Object>(0); 
        try { 
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
            for (int i = 0; i < descriptors.length; i++) { 
                String name = descriptors[i].getName(); 
                if (!"class".equals(name)) { 
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
                } 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return params; 
	}

}
